package com.isunland.managesystem.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;
import com.google.gson.Gson;
import com.isunland.managesystem.R;
import com.isunland.managesystem.adapter.CommonMessageAdapter;
import com.isunland.managesystem.base.BaseListFragment;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.entity.Rwjmessagepublic;
import com.isunland.managesystem.entity.RwjmessagepublicOriginalList;
import com.isunland.managesystem.utils.MyDateUtil;
import com.isunland.managesystem.utils.ParamsNotEmpty;
import com.isunland.managesystem.utils.ToastUtil;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;

@SuppressWarnings("deprecation") public class CommonMessageListFragment extends BaseListFragment {

  private static final int REQUEST_QUERY = 1;
  FragmentManager manager;
  private ArrayList<Rwjmessagepublic> mLatestAnnounceMent;
  private CommonMessageAdapter mLatestAnnounceMentAdapter;
  private EditText etannounceName;
  private Date mStartDate;//开始日期,默认周一
  private Date mEndDate;//结束日期,默认周日

  @Override public String getUrl() {
    return ApiConst.URL_COMMONMESSAGE_LIST;
  }

  @Override public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setBack(true);
    setTitleCustom(R.string.commonMessage);
    manager = getFragmentManager();
    mEndDate = new Date();//当天
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(mEndDate);
    calendar.add(Calendar.MONTH, -3); //获取开始日期
    mStartDate = calendar.getTime();
  }

  @Override public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    View header =
        getLayoutInflater(savedInstanceState).inflate(R.layout.header_search_person, mListview,
            false);
    etannounceName = (EditText) header.findViewById(R.id.et_search_searchPersonHeader);
    etannounceName.setHint(R.string.etannounceHint);
    etannounceName.addTextChangedListener(new MyTextWatcher());
    mListview.addHeaderView(header);
  }

  @Override public HashMap<String, String> getparameters() {

    ParamsNotEmpty params = new ParamsNotEmpty();
    params.put("startTime", MyDateUtil.parseDateToString(mStartDate));
    params.put("endTime", MyDateUtil.parseDateToString(mEndDate));
    params.put("dataStatus", "publish");
    params.put("manageOrgCode", mCurrentUser.getManageOrgCode());
    params.put("provinceName", mCurrentUser.getProvince());
    return params.getParams();
  }

  // 请求数据
  @Override public void resolveResponse(String param) {

    RwjmessagepublicOriginalList orginal =
        new Gson().fromJson(param, RwjmessagepublicOriginalList.class);
    mLatestAnnounceMent = orginal.getRows();
    setAdapter(mLatestAnnounceMent);
  }

  @Override public void onListItemClick(ListView l, View v, int position, long id) {

    Rwjmessagepublic detail = (Rwjmessagepublic) mLatestAnnounceMentAdapter.getItem(position - 2);
    Intent intent = new Intent(getActivity(), CommonMessageDetailActivity.class);

    intent.putExtra(CommonMessageDetailFragment.EXTRA_DETAIL, detail);
    startActivityForResult(intent, 0);
  }

  // 判断适配器中的announcement为空的情况进行处理
  public void setAdapter(ArrayList<Rwjmessagepublic> announceMent) {
    if (announceMent == null || announceMent.size() == 0) {
      announceMent = new ArrayList<>();
    }
    mLatestAnnounceMentAdapter = new CommonMessageAdapter<>(getActivity(), announceMent);
    setListAdapter(mLatestAnnounceMentAdapter);
    ((CommonMessageAdapter) getListAdapter()).notifyDataSetChanged();
  }

  /**
   * 标题模糊搜索
   */
  //	@Override
  //	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
  //		inflater.inflate(R.menu.menu_contacts_search, menu);
  //		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
  //
  //			//MenuItem searchItem = menu.findItem(R.id.menu_item_search);
  //			//SearchView searchView =(SearchView) MenuItemCompat.getActionView(searchItem);
  //            SearchView  searchView= (SearchView) MenuItemCompat.getActionView(menu.findItem(R.id.menu_item_search));
  //
  //			SearchManager searchManager = (SearchManager) getActivity()
  //					.getSystemService(Context.SEARCH_SERVICE);
  //			ComponentName name = getActivity().getComponentName();
  //			SearchableInfo searchInfo = searchManager.getSearchableInfo(name);
  //            if (searchView!=null){
  //
  //			searchView.setSearchableInfo(searchInfo);
  //
  //			searchView.setOnQueryTextListener(new OnQueryTextListener() {
  //
  //				@Override
  //				public boolean onQueryTextSubmit(String query) {
  //					return true;
  //				}
  //
  //				@Override
  //				public boolean onQueryTextChange(String newText) {
  //					if(mLatestAnnounceMent==null|| mLatestAnnounceMent.size()==0){
  //						return false;
  //					}
  //					if (TextUtils.isEmpty(newText)) {
  //						setAdapter(mLatestAnnounceMent);
  //					}else{
  //						updateItems(newText);
  //					}
  //
  //					return true;
  //				}
  //			});
  //            }
  //		}
  //
  //		super.onCreateOptionsMenu(menu, inflater);
  //	}
  public void updateItems(String query) {

    // 通过标题来进行搜索
    ArrayList<Rwjmessagepublic> titleNames = new ArrayList<>();
    String str;
    for (int i = 0; i < mLatestAnnounceMent.size(); i++) {
      str = mLatestAnnounceMent.get(i).getMessageHeader();
      if (null != str && str.contains(query)) {
        titleNames.add(mLatestAnnounceMent.get(i));
      }
    }

    if (titleNames.size() == 0) {
      // 弹出提示
      ToastUtil.show(R.string.nothisAnnouncement);
    }
    // 刷新列表
    setAdapter(titleNames);
    etannounceName.requestFocus();
  }

  /**
   * 文字监听
   */
  private class MyTextWatcher implements TextWatcher {

    @Override
    public void beforeTextChanged(CharSequence charSequence, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence charSequence, int start, int before, int count) {
      if (mLatestAnnounceMent == null || mLatestAnnounceMent.size() == 0) {
        return;
      }
      String query = etannounceName.getText().toString().trim();
      if (TextUtils.isEmpty(query)) {
        setAdapter(mLatestAnnounceMent);
        etannounceName.requestFocus();
      } else {
        updateItems(query);
      }
    }

    @Override public void afterTextChanged(Editable editable) {

    }
  }

  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.menu_query, menu);

    super.onCreateOptionsMenu(menu, inflater);
  }

  @Override public boolean onOptionsItemSelected(MenuItem item) {
    if (item == null) return false;
    switch (item.getItemId()) {

      case R.id.menu_item_query:

        QueryDateActivity.startActivityForResult(CommonMessageListFragment.this, mStartDate,
            mEndDate, REQUEST_QUERY);

        return true;
    }

    return super.onOptionsItemSelected(item);
  }

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode != Activity.RESULT_OK) return;
    if (requestCode == REQUEST_QUERY && data != null) {
      mStartDate = (Date) data.getSerializableExtra(QueryDateFragment.EXTRA_START_DATE);
      mEndDate = (Date) data.getSerializableExtra(QueryDateFragment.EXTRA_END_DATE);
      volleyPost();
      return;
    }

    super.onActivityResult(requestCode, resultCode, data);
  }
}
